package com.mission.shaco.warehouse.models.list

import android.app.AlertDialog
import android.app.Dialog
import android.content.AbstractThreadedSyncAdapter
import android.content.Context
import android.content.DialogInterface
import android.opengl.Visibility
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import com.mission.shaco.warehouse.R
import com.mission.shaco.warehouse.ScannerActivity
import com.mission.shaco.warehouse.models.Tool
import com.mission.shaco.warehouse.stockout.MultiActivity
import com.mission.shaco.warehouse.stockout.SingleActivity
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable
import java.lang.Integer.parseInt
import java.util.*

/**
 * Created by Administrator on 2017/6/20.
 */
public open class BaseList : Serializable {

    @Transient var jsonArray = JSONArray()
    @Transient var wrongItemArray = JSONArray()
    @Transient var completeArray = JSONArray()
    @Transient var pTimeArray = JSONArray()
    @Transient var lastTime:Long = 0
    @Transient var dialog: Dialog? = null
    @Transient var multiBuilder:AlertDialog.Builder? = null

    var batchNumber:String = ""
    var useTime:Long = 0
    var lifeTime:Long = 0
    var upload = 0;

    internal val FIRST_INDEX = 0
    internal val FILE_NAME = "listview_single"
    private val SER_FILE_NAME = "adapter_base";


    fun getList(): JSONArray {
        return jsonArray
    }

    fun saveUseTime(time:Long){
        useTime = time
    }

    fun removeFirst() {
        removePosition(FIRST_INDEX)
    }

    fun removePosition(position: Int){
        if (Build.VERSION.SDK_INT < 19) {
            jsonArray = Tool().JSONRemove(position, jsonArray)
        } else {
            jsonArray.remove(position)
        }
    }

    @Throws(JSONException::class)
    fun reloadData(jsonList: JSONArray) {
        jsonArray = jsonList
        lifeTime = System.currentTimeMillis()/1000
        completeArray = JSONArray()
        wrongItemArray = JSONArray()
        pTimeArray = JSONArray()
    }

    fun initLifeTime(){
        lifeTime = System.currentTimeMillis()/1000
    }

    fun moveToLast(position: Int){
        var js = jsonArray.get(position) as JSONObject
        removePosition(position)
        jsonArray.put(js)
    }


    @Throws(IOException::class)
    private fun writeObject(oos: ObjectOutputStream) {
        oos.defaultWriteObject()
        var allJson = JSONArray()
        allJson.put(0,jsonArray)
        allJson.put(1,completeArray)
        allJson.put(2,wrongItemArray)
        allJson.put(3,pTimeArray)
        oos.writeObject(allJson.toString())
    }

    public fun getInfo():JSONObject{
        var allJson = JSONObject()
        allJson.put("un_complete",jsonArray)
        allJson.put("complete",completeArray)
        allJson.put("wrong_complete",wrongItemArray)
        allJson.put("p_times",pTimeArray)
        return allJson
    }

    @Throws(ClassNotFoundException::class, IOException::class, JSONException::class)
    private fun readObject(ois: ObjectInputStream) {
        ois.defaultReadObject()
        var allJson = JSONArray(ois.readObject() as String)
        jsonArray = allJson.get(0) as JSONArray
        completeArray = allJson.get(1) as JSONArray
        wrongItemArray = allJson.get(2) as JSONArray
        pTimeArray = allJson.get(3) as JSONArray
        lastTime = useTime
    }

    fun showDialog( mContext: Context, adapter: BaseAdapter) {
        itemDo()

        if (multiBuilder==null) {
            // 构造软件下载对话框
            multiBuilder = AlertDialog.Builder(mContext)
            multiBuilder?.setTitle(R.string.pick_multi)
        }
        val inflater = LayoutInflater.from(mContext)
        val v = inflater.inflate(R.layout.pick_multi_qty, null)
        var btnMultiQty = v.findViewById(R.id.btnMultiQtyAll) as Button

        btnMultiQty.setOnClickListener{
            var changeQty = v.findViewById(R.id.edtQty) as EditText
            itemDo(parseInt(changeQty.getText().toString()))
            dialog?.dismiss()
            adapter.notifyDataSetChanged()
            (mContext as ScannerActivity).resetCompleteQty()

            if(jsonArray.length() == 0){
                (mContext as ScannerActivity).complete()
            }
            (mContext as ScannerActivity).saveRunState()
        }

        var needQty:TextView
        var stockDesc:TextView
        var multiQtyName:TextView
        var multiQty:TextView
        var changeQty:EditText

        8

        if(dialog == null) {
            multiQtyName = v.findViewById(R.id.multi_qty_name) as TextView
            multiQty = v.findViewById(R.id.multi_qty_qty) as TextView
            needQty = v.findViewById(R.id.multi_qty_needqty) as TextView
            stockDesc = v.findViewById(R.id.multi_qty_stock_desc) as TextView
            changeQty = v.findViewById(R.id.edtQty) as EditText
        }else{
            multiQtyName = dialog?.findViewById(R.id.multi_qty_name) as TextView
            multiQty = dialog?.findViewById(R.id.multi_qty_qty) as TextView
            needQty = dialog?.findViewById(R.id.multi_qty_needqty) as TextView
            stockDesc = dialog?.findViewById(R.id.multi_qty_stock_desc) as TextView
            changeQty = dialog?.findViewById(R.id.edtQty) as EditText
        }
        var item = getCurrentItem()

        multiQtyName?.setText(item.getString("znName"))
        multiQty?.setText(item.getString("qty_bak"))
        needQty?.setText(item.getString("qty"))
        changeQty?.setText(item.getString("qty_bak"))

        if(item.has("desc")) {
            stockDesc?.setText(item.getString("desc"))
        }else{
            stockDesc.visibility = View.INVISIBLE
        }

        multiBuilder?.setView(v)

        if(dialog == null) {
            dialog = multiBuilder?.create()
            dialog?.show()
        }else{
            if(dialog?.isShowing() == false){
                dialog?.show()
            }
        }
    }

    fun getCurrentItem():JSONObject{
        return jsonArray.get(FIRST_INDEX) as JSONObject
    }

    fun getCurrentQty():Int {
        var item = this.getCurrentItem()
        val qty = if (item.has("qty_bak"))  item.getString("qty_bak") else item.getString("qty")
        return parseInt(qty)
    }

    fun takeSuccess( mContext: Context, adapter: BaseAdapter ) {
        if(getCurrentQty() > 1) {
            showDialog(mContext,adapter)
        }else {
            itemDo()
        }
    }

    fun itemDo(){
        var qty:Int = getCurrentQty()
        var currentItem = getCurrentItem()
        if(qty > 1) {
            if(currentItem.has("qty_bak")) {
                currentItem.put("qty_bak", qty - 1)
            }else{
                currentItem.put("qty_bak", qty)
            }
        }else{
            itemDo(true)
        }
    }

    fun itemDo(pickQty:Int){
        var qty:Int = getCurrentQty()
        var currentItem = getCurrentItem()
        if(qty > 1 && pickQty < qty ) {
            currentItem.put("qty_bak", qty - pickQty)
        }else{
            itemDo(true)
        }
    }

    fun itemDo(all:Boolean){
        if(dialog != null) {
            dialog?.dismiss()
        }
        var currentItem = getCurrentItem()
        saveProductUseTime()
        completeArray.put(currentItem)
        removeFirst()
    }

    fun saveProductUseTime(){
        var obj : JSONObject = jsonArray.get(FIRST_INDEX) as JSONObject
        var pTime : JSONObject = JSONObject()
        pTime.put("id",obj.get("id"))
        pTime.put("stock",obj.get("stock"))
        pTime.put("useTime", useTime - lastTime )
        if(obj.has("grid")) {
            pTime.put("grid", obj.get("grid"))
        }
        pTime.put("qty",obj.get("qty"))
        pTimeArray.put(pTime)
        lastTime = useTime
    }

    fun getSize() :Int{
        return jsonArray.length() + completeArray.length() + wrongItemArray.length()
    }

    fun getCompeleteSize() :Int {
        return completeArray.length()
    }

    fun getWrongSize():Int {
        return wrongItemArray.length()
    }

    fun clear() {
        wrongItemArray = JSONArray()
        completeArray = JSONArray()
        pTimeArray = JSONArray()
        jsonArray = JSONArray()
        lastTime = 0
        useTime = 0
        upload = 0
    }
}